package com.ak.kaoyan.service.impl;


import com.ak.kaoyan.entity.Judge_Info;
import com.ak.kaoyan.service.JudgeService;
import com.ak.kaoyan.utils.CompilerUtils;
import com.ak.kaoyan.utils.ExecuteUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import java.util.List;

@Slf4j
@Service
public class JudgeServiceImpl implements JudgeService {

    @Autowired
    ExecuteUtils executeUtils;

    /**
     * 判断程序
     * @param input 输入
     * @param code  代码
     * @param type  代码类型
     * @return 返回程序判断结果
     */
    @Override
    public Judge_Info getResult(String input, String code, String type) {
        Judge_Info judge_info = new Judge_Info();
        if ("java".equals(type)) {
            log.info("开始编译----");
            DiagnosticCollector<JavaFileObject> compileCollector = new DiagnosticCollector<>();

            //获取编译结果
            byte[] classBytes;
            try {
                classBytes = CompilerUtils.compile(code, compileCollector);
            } catch (IllegalArgumentException e) {
                judge_info.setMessage("无效的类" + e.getMessage());
                return judge_info;
            }
            //如果编译不通过则打印错误信息
            if (classBytes == null) {
                List<Diagnostic<? extends JavaFileObject>> compileError = compileCollector.getDiagnostics();
                StringBuilder compileErrorRes = new StringBuilder();
                for (Diagnostic diagnostic : compileError) {
                    compileErrorRes.append("Compilation error at ");
                    compileErrorRes.append(diagnostic.getLineNumber());
                    compileErrorRes.append(".");
                    compileErrorRes.append(System.lineSeparator());
                }
                judge_info.setMessage(compileErrorRes.toString());
                return judge_info;
            }
            return executeUtils.execute_java(input, code, classBytes);
        }
        // 首先进行编译
        return null;
    }
}
